<?php

namespace Zhifubao;

use Illuminate\Support\Facades\Log;

class Client
{

    public $client;
    protected $baseUrl;
    protected $loggerChannel = 'alipay-raw';
    protected $appId;
    protected $logger;
    protected $maxTries;
    protected $alipayConfig;


    public function __construct($timeout = 30, $maxTries = 3)
    {
        $this->logger = Log::channel($this->loggerChannel);
        $this->baseUrl = config('alipay.base_url');
        $this->appId = config('alipay.app_id');
        $this->maxTries = $maxTries;


        $this->alipayConfig = new AlipayConfig();
        $this->alipayConfig->setServerUrl($this->baseUrl);
        $this->alipayConfig->setAppId($this->appId);
        $this->alipayConfig->setFormat("json");
        $this->alipayConfig->setCharset("UTF-8");
        $this->alipayConfig->setSignType("RSA2");
        $this->alipayConfig->setPrivateKey(file_get_contents(storage_path("app/hexinb.com_私钥.txt")));
        $this->alipayConfig->setAppCertPath(storage_path('app/appCertPublicKey_2021003122610846.crt'));
        $this->alipayConfig->setAlipayPublicCertPath(storage_path('app/alipayCertPublicKey_RSA2.crt'));
        $this->alipayConfig->setRootCertPath(storage_path('app/alipayRootCert.crt'));

    }

    public function request($request)
    {
        $client = new AopCertClient($this->alipayConfig);
        $result = $client->execute($request);


        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";

        if ($result->$responseNode->code != '10000') {
            $this->logger->error('错误', [
                'api' => $request->getApiMethodName(),
                'biz' => $request->getBizContent(),
                'response' => $result,
            ]);
        } else {
            $this->logger->info('请求', [
                'api' => $request->getApiMethodName(),
                'biz' => $request->getBizContent(),
                'response' => $result,
            ]);
        }


        return $result->$responseNode;
    }


    public function pageRequest($request)
    {
        $client = new AopCertClient($this->alipayConfig);

        $result = $client->pageExecute($request);


        return $result;
    }


}
